import axios from 'axios'
import {ElMessage} from "element-plus";

const request = axios.create({
  // 基础路径
  baseURL: import.meta.env.VITE_API_URL,
  // 超时时间，10s
  timeout: 10000
})

// 请求拦截器
request.interceptors.request.use(( config) => {
  return config
})

// 响应拦截器
request.interceptors.response.use((res) => {
  return res.data
},(error) => {
  let msg = ''
  const status = error.response.status
  switch (status) {
    case 401:
      msg = 'token过期'
      break
    case 403:
      msg = '无权访问'
      break
    case 404:
      msg = '请求地址错误'
      break
    case 500:
      msg = '服务器出现错误'
      break
    default:
      msg = '网络出现错误'
      break
  }
  ElMessage({
    type: 'error',
    message: msg
  })

  return Promise.reject(error)
})

class Result {
  constructor(code, msg) {
    this.code = code
    this.msg = msg
  }
}

class ContentResult extends Result {
  constructor(code, msg, data) {
    super(code, msg)
    this.data = data
  }
}

/**
 * GET
 * @param url
 * @param params
 * @returns {Promise<axios.AxiosResponse<any>>}
 */
export function doGet(url, params = {}) {
  return request.get(url, {params})
}

/**
 * PUT
 * @param url
 * @param data
 * @returns {Promise<axios.AxiosResponse<any>>}
 */
export function doPut(url, data = {}) {
  return request.put(url, data)
}

/**
 * POST
 * @param url
 * @param data
 * @returns {Promise<axios.AxiosResponse<any>>}
 */
export function doPost(url, data = {}) {
  return request.post(url, data, {
    headers: {
      'Content-Type': 'application/json'
    }
  })
}

/**
 * POST FORM
 * @param url
 * @param data
 * @returns {Promise<axios.AxiosResponse<any>>}
 */
export function doPostFormData(url, data = {}) {
  return request.postForm(url, data, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }})
}

export function doPostForm(url, data = {}) {
  return request.postForm(url, data, {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }})
}

